<template>
  <div class="org-main-container">
    <org-main-header ref="mainHeader" :title="mainTitle" :title-type="mainType" />
    <org-main-operator ref="mainOperator" @on-operation="onOperation" />
    <org-main-table
      ref="mainTable"
      :main-id="mainId"
      :style="tableStyle"
      @on-show-detail="onShowDetail"
      @selection-change="onSelectChange"
    />
    <add-user ref="addUser" @added="flushData" @no-auth="onNoAuth" />
    <detail-user ref="detailUser" @on-delete="onDeleteUser" @on-update="onUpdateUser" />
    <import-user ref="importUser" @import-success="flushData" />
    <export-user ref="exportUser" />
    <move-user ref="moveUser" @moved="flushData" />
    <org-auth ref="orgAuth" />
    <sort-column ref="sortColumn" />
  </div>
</template>

<script>
  import { mapGetters } from 'vuex';

  import OrgMainHeader from './OrgMainHeader';
  import OrgMainOperator from './OrgMainOperator';
  import OrgMainTable from './OrgMainTable';
  import AddUser from '../drawer/AddUser';
  import DetailUser from '../drawer/DetailUser';
  import ImportUser from '../drawer/ImportUser';
  import ExportUser from '../drawer/ExportUser';
  import MoveUser from '../modal/MoveUser';
  import OrgAuth from '../drawer/OrgAuth';
  import SortColumn from '../modal/SortColumn';

  import { deleteUser, getUserdetail } from '@/api/organization';

  export default {
    components: {
      OrgMainHeader,
      OrgMainOperator,
      OrgMainTable,
      AddUser,
      DetailUser,
      ImportUser,
      ExportUser,
      MoveUser,
      OrgAuth,
      SortColumn,
    },
    props: {
      mainId: {
        type: Number,
        required: true,
      },
      mainTitle: {
        type: String,
        required: true,
      },
      mainType: {
        type: String,
        required: true,
      },
    },
    data() {
      return {
        selectedIds: [],
      };
    },
    computed: {
      ...mapGetters('user', ['userInfo']),
      ...mapGetters('organization', ['orgTree']),
      organizationId() {
        return this.userInfo.organId;
      },
      hasDept() {
        const tree = this.orgTree || [];
        return (
          (tree &&
            tree[0] &&
            tree[0].organizationTreeVo &&
            tree[0].organizationTreeVo.length > 0) ||
          false
        );
      },
      tableStyle() {
        return { height: `calc(100% - ${114}px)` };
      },
    },
    methods: {
      onOperation(name, way) {
        const open = () => {
          const refComp = this.$refs[name];
          refComp &&
            refComp.onOpen({
              mainId: this.mainId,
              mainTitle: this.mainTitle,
              mainType: this.mainType,
              organizationId: this.organizationId,
              selectedIds: this.selectedIds,
            });
        };

        switch (way) {
          case 'drawer':
            open();
            break;
          case 'modal':
            if (name === 'sortColumn') {
              open();
              break;
            }

            if (!this.hasDept) {
              this.$message('没有部门可以调整，请先增加子部门');
              break;
            }
            name === 'moveUser' && this.selectedIds.length > 0
              ? open()
              : this.$message('没有人员被选中');
            break;
          case 'msg':
            const confirmDeleteUser = () => {
              this.$confirm('删除所选员工，将会清除所选员工资料，是否确定删除？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
              }).then(() => {
                this.deleteUser();
              });
            };
            name === 'deleteUser' && this.selectedIds.length > 0
              ? confirmDeleteUser()
              : this.$message('没有人员被选中');
            break;
          default:
            break;
        }
      },
      onShowDetail(row) {
        getUserdetail({
          organizationId: this.organizationId,
          staffId: row.id,
        }).then(res => {
          this.$refs['detailUser'].onOpen(res.data);
        });
      },
      async onDeleteUser(data) {
        this.selectedIds = [data.id];
        this.deleteUser();
      },
      onUpdateUser(data) {
        this.$refs['addUser'].onEdit(data);
      },
      goAuth() {
        this.$refs['orgAuth'].onOpen(this.organizationId);
      },
      onSelectChange(items) {
        this.selectedIds = items.map(item => item.id);
      },
      async deleteUser() {
        await deleteUser({ staffIds: this.selectedIds });
        this.flushData();
      },
      onImportUserSuccess() {
        this.flushData();
      },
      flushData() {
        this.$refs['mainTable'].flushTable();
        this.$store.dispatch('organization/initOrgTree', this.organizationId);
      },
      onNoAuth(message) {
        this.$confirm(message, '提示', {
          distinguishCancelAndClose: true,
          confirmButtonText: '确定',
          cancelButtonText: '去认证',
          type: 'warning',
        }).catch(action => {
          // 去认证
          if (action === 'cancel') {
            this.$refs['orgAuth'].onOpen(this.organizationId);
          }
        });
      },
    },
  };
</script>

<style lang="scss" scoped>
  .org-main-container {
    height: 100%;
  }
</style>
